<template>
  <!-- 统计分析 -->
  <div class="statistic_wrap">
    <!-- 搜索 -->
    <div class="search">
      <span>公司/部门名称：</span>
      <el-select v-model = "queryParam.orgCode" 
        style = "width:154px;margin-right:20px;height:36px">
        <el-option
          v-for = "(item, index) in orgCodeOptions"
          :key = "index"
          :label = "item.orgName"
          :value = "item.orgCode"
        ></el-option>
      </el-select>
      <span class = "demonstration">支出时间：</span>
      <el-date-picker
        placeholder = "开始日期"
        style = "width:160px;margin-right:12px"
        v-model = "queryParam.startTime" 
        :clearable = "false"
        value-format="yyyy-MM"
        type="month"
        :picker-options="startPickerOptions"
      ></el-date-picker>至
      <el-date-picker
        placeholder = "结束日期"
        style = "width:160px;margin-left:12px"
        v-model = "queryParam.endTime"
        :clearable = "false"
        value-format="yyyy-MM"
        type="month"
        :picker-options="endPickerOptions"
      ></el-date-picker>
      <el-button
        type="primary"
        @click="query()"
        style="width:52px;margin-left: 20px;padding:0px;height:36px"
      >查询</el-button>
      <el-button
        style="width:52px;margin-left: 12px;padding:0px;height:36px"
        @click="resetQueryParam"
      >重置</el-button>
    </div>
    <!-- new echarts -->
    <div class="echartsContiner" style="position:relative;">
      <div class="echartsTitle">
        <span>费用走势图</span>
        <!-- <div class="toggleTitle">
          <ul>
            <li :class="activeFeesDate === '0' ? 'active' : ''" @click="toggleFeesDate('0')">日</li>
            <li :class="activeFeesDate === '1' ? 'active' : ''" @click="toggleFeesDate('1')">月</li>
          </ul>
        </div> -->
      </div>
      <div class="trend_chart" id="trendChart" style="transform:translateY(20px);height:350px;" ></div>
      <div v-show="falseData.length === 0" style="transform:translateY(20px);height:350px;display:flex;align-items:center;justify-content:center;position: absolute; width: 100%; background: #fff; top: 40px;">
        <span>暂无数据</span>
      </div>
    </div>
    <div class="second_statistic_wrap">
      <div class="rate_chart_statstic" style="position:relative;">
        <div class="rate_head_title">各类别占比</div>
        <div class="rate_chart" id="rateChart" style="transform:translateX(-100px)"></div>
        <div class="rate_chart" v-if="categoryFalseData.length === 0" style="display:flex;align-items:center;justify-content:center;position: absolute; width: 100%; background: #fff; top: 40px;">
          <span>暂无数据</span>
        </div>
      </div>
      <div class="bar_chart_statstic" style="position:relative;">
        <div class="bar_head_title">分类明细</div>
        <div class="bar_chart" v-if="classificationFalseData.length === 0" style="display:flex;align-items:center;justify-content:center;position: absolute; width: 100%; background: #fff; top: 40px;">
          <span>暂无数据</span>
        </div>
        <div class="bar_chart" id="barChart" style="transform:translateY(-40px)"></div>
      </div>
    </div>
  </div>
</template>
<script>
import {formatDate} from "@/utils/tools"
import echarts from "echarts";
let _that
export default {
  components: {},
  props: {
    orgCodeOptions: {
      type: Array,
      default: () => {
        return []
      },
    },
    feesCodeOptions: {
      type: Array,
      default: () => {
        return []
      },
    }
  },
  data() {
    return {
      queryParam: {
        orgCode: "",
        startTime: formatDate(new Date((new Date().getFullYear()-1) +'-'+ (new Date().getMonth() + 1)), 'yyyy-MM'),
        endTime: formatDate(new Date(), 'yyyy-MM'),
      },
      startPickerOptions: {
          disabledDate(time) {
          return _that.queryParam.endTime ? (time.getTime() > new Date(_that.queryParam.endTime).getTime()) : ''
          }
      },
      endPickerOptions: {
          disabledDate(time) {
          return _that.queryParam.startTime ? (time.getTime() < new Date(_that.queryParam.startTime).getTime()) : ''
          }
      },
      // 费用走势图数据
      falseData: [],
      categoryFalseData: [],
      classificationFalseData:[],
      activeFeesDate:'1', //0-日 1-月
      colorData: [
        "rgba(102, 153, 255, 1)",
        "rgba(61, 127, 255, 1)",
        "rgba(102, 153, 255, 1)",
        "rgba(161, 230, 206, 1)",
        "rgba(82, 204, 163, 1)",
        "rgba(149, 128, 255, 1)",
        "rgba(191, 179, 255, 1)",
        "rgba(179, 205, 255, 1)",
        "rgba(125, 143, 179, 1)",
        "rgba(240, 189, 127, 1)",
        "rgba(106, 205, 237, 1)",
        "rgba(102, 153, 255, 1)",
      ],
      
    
    };
  },
  created() {},
  mounted() {
    _that = this
    // this.makeTrendChart();
    // this.makeRateChart();
    // this.makeTypeChat();
    this.queryData()
  },
  methods: {
    // 查询事件调用
    queryData() {
      let data = JSON.parse(JSON.stringify(this.queryParam))
      this.gettpConsumptionGetTrend(data)
      this.gettpConsumptiongGetCategory(data)
      this.gettpConsumptiongGetClassification(data)
    },
    // 查询按钮事件
    query() {
      this.queryData()
    },
    // 重置按钮事件
    resetQueryParam() {
      Object.assign(this.$data.queryParam, this.$options.data().queryParam);
      this.queryData()
    },
    // 动态监督-三公消费统计-走势图
    gettpConsumptionGetTrend(data) {
        this.Api.gettpConsumptionGetTrend(data).then(res => {
          if(res && res.code === '0') {
            this.falseData = res.data
            this.makeTrendChart()
          } else {
            this.falseData = []
            this.$message.warning(res.message)
          }
        })
    },
    // 动态监督-三公消费统计-各类别占比
    gettpConsumptiongGetCategory(data) {
      this.Api.gettpConsumptiongGetCategory(data).then(res => {
          if(res && res.code === '0') {
             this.categoryFalseData = res.data.classificationList
             this.makeRateChart()
          } else {
            this.categoryFalseData = []
            this.$message.warning(res.message)
          }
        })
    },
    // 动态监督 - 三公消费统计 - 分类明细
    gettpConsumptiongGetClassification(data) {
      this.Api.gettpConsumptiongGetClassification(data).then(res => {
          if(res && res.code === '0') {
            this.classificationFalseData = res.data
            this.makeTypeChat()
          } else {
            this.classificationFalseData = []
            this.$message.warning(res.message)
          }
        })
    },
    // 切换 日 月
    toggleFeesDate(value) {
      if(this.activeFeesDate !== value) {
        this.activeFeesDate = value
        this.makeTrendChart()
      }
    },

    //绘制 费用走势图
    makeTrendChart() {
      if(this.falseData.length === 0) return
      // 图例组件数据
      let feesCodeNameArray = []
      let MaxDate= '' // 最大日期
      let MinDate = '' // 最小日期
      let monthArray = [] // 月份
      let dayArray = [] // 日期
      let xAxisData = [] // X轴展示数据
      // 相同日期&&相同科目的 金额相加
      let sameDateAndFeesName = {}
      let overMillion = false
      this.falseData.forEach((item, index) => {
        // 获取最小日期和最大日期
        if (this.activeFeesDate === '0') {
          MaxDate = MaxDate && (new Date(MaxDate).getTime() > new Date(item.period).getTime()) ? MaxDate : item.period
          MinDate = MinDate && (new Date(MinDate).getTime() < new Date(item.period).getTime()) ? MinDate : item.period
        }else if (this.activeFeesDate === '1') {
          MaxDate = MaxDate && (new Date(MaxDate).getTime() > new Date(item.period).getTime()) ? MaxDate : item.period
          MinDate = MinDate && (new Date(MinDate).getTime() < new Date(item.period).getTime()) ? MinDate : item.period
        }

        if(!sameDateAndFeesName[item.feesName]) sameDateAndFeesName[item.feesName] = {data: []}
        if (sameDateAndFeesName[item.feesName][item.period]) {
          sameDateAndFeesName[item.feesName][item.period] = Number(sameDateAndFeesName[item.feesName][item.period]) + Number(item.amount)
        } else {
          sameDateAndFeesName[item.feesName][item.period] = Number(item.amount)
        }
        if(sameDateAndFeesName[item.feesName][item.period] >= 10000) {
          overMillion = true
        }

        // if(sameDateAndFeesName[item.feesName][item.period.substr(0, item.period.lastIndexOf('-'))]) {
        //   sameDateAndFeesName[item.feesName][item.period.substr(0, item.period.lastIndexOf('-'))] = sameDateAndFeesName[item.feesName][item.period.substr(0, item.period.lastIndexOf('-'))] + Number(item.amount)
        // } else {
        //   sameDateAndFeesName[item.feesName][item.period.substr(0, item.period.lastIndexOf('-'))] = Number(item.amount)
        // }
      })

      this.feesCodeOptions.forEach((item, index) => {
        if (item.value !== '' && !sameDateAndFeesName[item.name]) {
          sameDateAndFeesName[item.name] = {data: []}
        }
      })
      if (this.activeFeesDate === '0') {
        // 日的数据处理
        dayArray = this.getdiffdate(MinDate, MaxDate)
        dayArray.forEach(item => {
          for (let key in sameDateAndFeesName) {
            sameDateAndFeesName[key].data.push(sameDateAndFeesName[key][item] ? (overMillion ? (Number(sameDateAndFeesName[key][item]) / 10000).toFixed(2) : sameDateAndFeesName[key][item]) : 0)
          }
        })
      } else if (this.activeFeesDate === '1') {
        // 月的数据处理
        monthArray = this.getMonthBetween(MinDate, MaxDate)
        monthArray.forEach(item => {
          for (let key in sameDateAndFeesName) {
            sameDateAndFeesName[key].data.push(sameDateAndFeesName[key][item] ? (overMillion ? (Number(sameDateAndFeesName[key][item]) / 10000).toFixed(2) : sameDateAndFeesName[key][item]) : 0)
          }
        })
      }
      // 初始化数据
      let seriesDatas = []
      // let legendSelected = {}
      this.feesCodeOptions.forEach((item, index) => {
        let result = {}
        let _that = this

        if (item.value !== '') {
          // legendSelected[item.name] = Object.keys(legendSelected).length === 0 ? true : false
          feesCodeNameArray.push(item.name)
          result.areaStyle = {
            color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              { offset: 0, color: _that.colorData[index].replace("1)", "0.1)"), },
              { offset: 0.6, color: _that.colorData[index].replace("1)", "0.2)"), },
              { offset: 1, color: _that.colorData[index].replace("1)", "0.8)"), },
            ]),
          }
          result.data = sameDateAndFeesName[item.name].data
          result.itemStyle = {color: this.colorData[index]}
          result.name = item.name
          result.smooth = true
          result.type = "line"
          seriesDatas.push(result)
        }
        
      })
      let optionData = {
        title: {
          subtext: "单位:"+ overMillion ? '万元' : '元',
          left: 20,
          top: 40,
          textStyle: {
            color: '#999999',
            fontSize: 12
          }
        },
        legend: {
          data: feesCodeNameArray,
          top: 0,
          left: 10,
          padding:20,
          textStyle: {
            color: '#666666',
            fontSize: 12
          },
          // selected: legendSelected
        },
        grid: {
            top: 100,
            bottom: 40,
            left:60,
            right:40,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            label: {
              backgroundColor: "#6a7985", // 指针的颜色
            },
          },
          position: function (pt) {
            return [pt[0], "10%"];
          },
        },
        xAxis:{
          type: 'category',
          boundaryGap: false,
          axisTick: {
            show: false,
          },
          nameTextStyle:{
            color: '#666666',
          },
          data: this.activeFeesDate === '0' ? dayArray : monthArray,
        },
        yAxis: {
          type: "value",
          axisTick: {
            show: false,
          },
          // 设置 y轴样式
          axisLine: {
            lineStyle: {
              width: 0, // 粗细
            },
          },
          nameTextStyle:{
            color: '#666666',
          },
          // 设置网格线样式
          splitLine: {
            show: true,
            lineStyle: {
              width: 1,
              type: "dashed",
            },
          },
        },
        series: seriesDatas
      }
      // 基于准备好的dom，初始化echarts实例
      let myChart = echarts.init(document.getElementById("trendChart"));
     
      // 绘制图表
      myChart.setOption(optionData);
    },
    // 绘制类别占比图
    makeRateChart() {
      // 分装 dataType
      let newDataType = [];
      let newData = [];
      
      this.categoryFalseData.forEach(item => {
        newDataType.push({icon:'circle', name: item.feesName})
        newData.push({value:item.amount, name: item.feesName})
      })
      this.feesCodeOptions.forEach(item => {

      }) 
      let option = {
        color: [
          "#6ACDED",
          "#F0BD7F",
          "#7D8FB3",
          "#B3CDFF",
          "#BFB3FF",
          "#9580FF",
          "#52CCA3",
          "#A1E6CE",
          "#6699FF",
        ],
        legend: {
          orient: "vertical",
          right: -16,
          top: 30,
          data: newDataType,
        },
        tooltip: {
          trigger: "item",
          formatter: "{d}%<br/>{b} : {c}",
        },
        grid: {
            top: 100,
            bottom: 40,
            left:60,
            right:40,
        },
        series: [
          {
            name: "各类别占比",
            type: "pie",
            radius: ["30%", "60%"],
            labelLine: {
              normal: {
                length: 20, // 改变标示线的长度
              },
            },
            label: {
              show: true,

              formatter: "{d}% ", //区域名称用b1111的样式
              rich: {
                b1111: {
                  fontSize: 12,
                  lineHeight: 33,
                  top: 100,
                },
                c: {
                  fontSize: 12,
                  lineHeight: 33,
                },
              },
            },
            // 选中状态样式
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },

            data: newData,
          },
        ],
      };
      echarts.init(document.getElementById("rateChart")).setOption(option);
    },
    // 绘制分类明细图
    makeTypeChat() {
      let newDataType = []
      let newData = []
      this.classificationFalseData.forEach(item => {
        newDataType.push(item.feesName)
        newData.push(item.amount)
      })
      let option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {},
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          axisTick: {
            show: false,
          },
          // 设置 y轴样式
          axisLine: {
            lineStyle: {
              width: 0, // 粗细
            },
          },
          // 设置网格线样式
          splitLine: {
            show: true,
            lineStyle: {
              width: 0,
            },
          },
        },
        yAxis: {
          type: "category",
          data: newDataType,
          axisTick: {
            show: false,
          },

          axisLine: {
            lineStyle: {
              color: "#666", // 颜色
              width: 0, // 粗细
            },
          },
        },
        series: [
          {
            type: "bar",
            data: newData,
            barWidth: 8,
            itemStyle: {
              normal: {
                barBorderRadius: [10, 10, 10, 10],
                color: function (params) {
                  let colorList = [
                    "#6ACDED",
                    "#F0BD7F",
                    "#7D8FB3",
                    "#B3CDFF",
                    "#BFB3FF",
                    "#9580FF",
                    "#52CCA3",
                    "#A1E6CE",
                    "#6699FF",
                  ];
                  return colorList[params.dataIndex];
                },
              },
            },
          },
        ],
      };
      echarts.init(document.getElementById("barChart")).setOption(option);
    },
    // 获取两个日期中所有的月份/日期
    getMonthBetween(start,end){ 
      var result = [];  
      var s = start.split("-");
      var e = end.split("-");
      var min = new Date();  
      var max = new Date();  
      min.setFullYear(s[0],s[1]-1);  
      max.setFullYear(e[0],e[1]-1);  
      var curr = min;  
      while(curr <= max){  
          var month = curr.getMonth();
          var str=curr.getFullYear()+"-"+((Number(month)+1) >= 10 ? (Number(month)+1) : ('0' + (Number(month)+1)));
          var s=curr.getFullYear()+"-0";
          if(str==s){
            str=curr.getFullYear()+"-12";
          }
          result.push(str);  
          curr.setMonth(month+1);
      }
      return result;  
    },
 
    //获取两日期之间日期列表函数
    getdiffdate(stime,etime){
      //初始化日期列表，数组
      var diffdate = new Array();
      var i=0;
      //开始日期小于等于结束日期,并循环
      while(stime<=etime){
        diffdate[i] = stime;
        //获取开始日期时间戳
        var stime_ts = new Date(stime).getTime();
        //增加一天时间戳后的日期
        var next_date = stime_ts + (24*60*60*1000);   
        //拼接年月日，这里的月份会返回（0-11），所以要+1
        var next_dates_y = new Date(next_date).getFullYear()+'-';
        var next_dates_m = (new Date(next_date).getMonth()+1 < 10)?'0'+(new Date(next_date).getMonth()+1)+'-':(new Date(next_date).getMonth()+1)+'-';
        var next_dates_d = (new Date(next_date).getDate() < 10)?'0'+new Date(next_date).getDate():new Date(next_date).getDate();
        stime = next_dates_y+next_dates_m+next_dates_d;
        //增加数组key
        i++;
      }
      return diffdate
    }
  },
};
</script>
<style lang="less" scoped>
.statistic_wrap {
  width:100%;
  display: flex;
  flex-direction: column;
  // 搜索
  .search {
    padding:0 20px 20px 20px;
    background: #fff;
    width:100%;
    /deep/ .el-input__inner {
      height: 36px;
    }
    /deep/.el-icon-date
    {
      line-height: 36px;
      position: absolute;
		  left: 120px;
    }
    /deep/.el-icon-arrow-up{
      line-height: 36px;
    }
  }
  // new
  .echartsContiner{
    padding:0 20px 20px 20px;
    background:#fff;
    .echartsTitle {
      display: flex;
      justify-content: space-between;
      font-size: 16px; 
      padding:0 24px;
      color: #333333;
      font-weight: 600;
      font-family: PingFangSC-Medium, PingFang SC;
      border-bottom: 1px solid #eeeeee;
      .toggleTitle{
        ul{
          display: flex;
          list-style: none;
          li{
            width:48px;
            text-align: center;
            font-size: 16px;
            line-height: 50px;
          }
          .active{
              border-bottom: 2px solid #1677FF;
              color: #1677FF;
            }
        }
      }
    }
  }
  
  // old Echarts
  .trend_chart_wrap {
    height: 350px;
    padding: 0 24px;
    background: #fff;
    .trend_head {
      height: 60px;
      line-height: 60px;
      font-weight: 600;
      font-size: 16px;
      border-bottom: 1px solid #eee;
      display: flex;
      padding: 0 24px;
      .trend_head_title {
        flex: 1;
      }
      .trend_head_select {
        flex: 1;
        text-align: right;
        ul {
          li {
            display: inline-block;
            width: 48px;
            text-align: center;
          }
          li.active {
            color: #3d7fff;
            border-bottom: 2px solid #3d7fff;
          }
        }
      }
    }
    .trend_chart {
      height: 280px;
      width: 1510px;
    }
  }
  .second_statistic_wrap {
    height: 330px;
    border-top: 20px solid #f0f2f5;
    display: flex;
    
    .rate_chart_statstic {
      width: 600px;
      height: 360px;
      padding: 0 24px 20px 24px;
      background: #fff;
      margin-right: 20px;
      .rate_head_title {
        height: 60px;
        line-height: 60px;
        font-size: 16px;
        color: #333;
        font-weight: 600;
        border-bottom: 1px solid #eee;
        padding: 0 24px;
      }
      .rate_chart {
        width: 600px;
        height: 280px;
      }
    }
    .bar_chart_statstic {
      height: 360px;
      width: 960px;
      padding: 0 24px 20px 24px;
      background: #fff;
      .bar_head_title {
        height: 60px;
        line-height: 60px;
        font-size: 16px;
        color: #333;
        font-weight: 600;
        border-bottom: 1px solid #eee;
        padding: 0 24px;
      }
      .bar_chart {
        width: 940px;
        height: 300px;
      }
    }
  }
}
</style>